package com.zklh.leetcode.interviewTop150;

import java.util.HashSet;
import java.util.Set;

/**
 * 有效的数独
 *
 * @Author tongnan
 * @Date 2024/6/28
 * @Version 1.0
 */
public class Solution36 {
    public boolean isValidSudoku(char[][] board) {
        Set<Character> characters = new HashSet<>();

        for (int i = 0; i < 9; i++) {
            // 检索横向是否冲突
            characters.clear();
            for (int j = 0; j < 9; j++) {
                if ('.' == board[i][j]) {
                    continue;
                }
                if (characters.contains(board[i][j])) {
                    return false;
                }
                characters.add(board[i][j]);
            }

            // 纵向是否冲突
            characters.clear();
            for (int j = 0; j < 9; j++) {
                if ('.' == board[j][i]) {
                    continue;
                }
                if (characters.contains(board[j][i])) {
                    return false;
                }
                characters.add(board[j][i]);
            }
        }

        for (int i = 0; i < 9; i+=3) {
            for (int j = 0; j < 9; j+=3) {
                characters.clear();
                for (int x = 0; x < 3; x++) {
                    for (int y = 0; y < 3; y++) {
                        if ('.' == board[i+x][j+y]) {
                            continue;
                        }
                        if (characters.contains(board[i+x][j+y])) {
                            return false;
                        }
                        characters.add(board[i+x][j+y]);
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution36 solution36 = new Solution36();
    }
}